<?php
/**
 * 核心文件
 * User: 叶华盛
 * Date: 2017/8/9
 * Time: 17:05
 */
namespace core;
class App
{
    //路由
    protected static $router;

    public static function run()
    {
        //获取uri的配置
        self::$router   =   new Router();
        //安全处理
        //APP_M
        $module = self::$router->getModule();
        preg_match('/^[_a-zA-Z0-9]\w+$/', $module) ? true : die('{"status":0,"errorcode":500,"errormsg":"module is error！"}');
        $controller_class = ucfirst(self::$router->getController()) . 'Controller';
        //APP_C
        preg_match('/^[_a-zA-Z0-9]\w+$/', $controller_class) ? true : die('{"status":0,"errorcode":500,"errormsg":"controllers is error！"}');
        $method = ucfirst(self::$router->getAction());
        //APP_A
        preg_match('/^[_a-zA-Z0-9]\w+$/', $method) ? true : die('{"status":0,"errorcode":500,"errormsg":"action is error！"}');
        define('MODULE', self::$router->getModule());
        define('CONTROLLER', self::$router->getController());
        define('ACTION', self::$router->getAction());
        $controller_class   =   'controllers'.DS.$module.DS.$controller_class;
        
        if( !file_exists( ROOT.$controller_class.PHP_SUFFIX.EXT ) )
            die('{"status":0,"errorcode":404,"errormsg":"Api Address Does Not Exist！"}');

        $controller_class = str_replace(DS, '\\', $controller_class);

        //运行
        /**
         * 是否开启自动SESSION
         */
        if (ini_get(SESSION_AUTO_START) === false) {
            if (SESSION_AUTO_START === true) {
                /**
                 * session丢失处理
                 */
                if (Request::get('request', session_name())) {
                    session_id(Request::get('request', session_name()));
                }
                session_start();
            }
        }
        $controller = new $controller_class();
        if (method_exists($controller, $method)) {
            self::methodWork($controller->$method());
        } else {
            die('{"status":0,"errorcode":404,"errormsg":"Api Address Action Does Not Exist！"}');
        }
    }

    /**
     * controller处理后的返回数据处理输出
     * @param $param
     */
    public static function methodWork($param)
    {
        if (!$param) {
            return;
        }
        self::methodAjax($param);
        return;
    }

    /**
     * ajax输出处理
     * @param $param
     */
    public static function methodAjax($param)
    {
        header('Content-type: application/json;charset=utf-8');
        header('Cache-Control:no-cache,must-revalidate');
        header('Pragma:no-cache');
        //ajax输出配置
        $callback   =   json_encode_cn($param);
        //记录日志
        self::writeLog($callback);
        echo $callback;
        exit;
    }

    /**
     * 记录日志
     * @param $callback
     */
    private static function writeLog($callback)
    {
        $postData   =   file_get_contents('php://input');
        $appcode    =   Request::get('get','appcode');
        if( !is_dir(LOG_PATH.date('Ymd',time())) )
            mkdir(LOG_PATH.date('Ymd',time()),0777,true);
        $saveFile       =   fopen(LOG_PATH.date('Ymd',time()).DS.$appcode.'.log','a+');
        $savData        =   date('Y-m-d H:i:s',time()).'--'.'fromIp:'.getIp().'--fromUrl:'. $_SERVER['REQUEST_URI'].'--postData:'.($postData?$postData:NULL).'--callbackData:'.$callback."\n\r";
        fwrite($saveFile, $savData);
        fclose($saveFile);
        if( is_dir(LOG_PATH.date('Ymd',strtotime('-3 month'))) )
            self::delLogDir(LOG_PATH.date('Ymd',strtotime('-3 month')));
    }

    /**
     * 删除日志目录
     * @param $directory
     */
    private static function delLogDir($directory)
    {
        //自定义函数递归的函数整个目录
        if(file_exists($directory))
        {
            //判断目录是否存在，如果不存在rmdir()函数会出错
            if($dir_handle=@opendir($directory))
            {
                //打开目录返回目录资源，并判断是否成功
                while($filename=readdir($dir_handle))
                {
                    //遍历目录，读出目录中的文件或文件夹
                    if($filename!='.' && $filename!='..')
                    {
                        //一定要排除两个特殊的目录
                        $subFile=$directory.'/'.$filename;//将目录下的文件与当前目录相连
                        if(is_dir($subFile))
                        {
                            //如果是目录条件则成了
                            self::delLogDir($subFile);//递归调用自己删除子目录
                        }
                        if(is_file($subFile))
                        {
                            //如果是文件条件则成立
                            @unlink($subFile);//直接删除这个文件
                        }
                    }
                }
                closedir($dir_handle);//关闭目录资源
                rmdir($directory);//删除空目录
            }
        }
    }

    /**
     * 加载lib库类
     * @param $path
     * @return bool
     */
    public static function single($path)
    {
        if( empty( $path ) ) return false;
        $path   =   explode('_',$path);
        $controller_class   =   '';
        if( !empty($path[count($path)-1]) )
            $path[count($path)-1]   =   ucfirst($path[count($path)-1]);

        foreach( $path as $val )
            $controller_class   .=  DS.$val;

        switch ($path[0])
        {
            case 'ctl':
                $controller_class    =   'controllers'.str_replace('ctl'.DS,'',$controller_class).'Controller';
                break;
            case 'mod':

                $controller_class    =   'models'.str_replace('mod'.DS,'',$controller_class).'Model';
                break;
            default:
                $controller_class    =   'lib'.$controller_class;
        }
        if( !file_exists(ROOT.$controller_class.PHP_SUFFIX.EXT) )
            return false;

        $controller_class = str_replace(DS, '\\', $controller_class);

        return new $controller_class();
    }
}